package online.hxstar.learn.chapter2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author xinghu
 * @version 1.0
 * @date 2019/11/7 5:22 下午
 */
@Slf4j
public class EchoClient {

	private final String host;
	private final int port;

	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 创建 Bootstrap
			Bootstrap bootstrap = new Bootstrap();
			// 指定 EventLoopGroup 以 处理客户端事件;需要适 用于 NIO 的实现
			bootstrap.group(group)
					//适用于 NIO 传输的 Channel 类型
					.channel(NioSocketChannel.class)
					//设置服务器的InetSocketAddr- ess
					.remoteAddress(new InetSocketAddress(host, port))
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							//在创建 Channel 时 向 ChannelPipeline 中添加一个 Echo- ClientHandler 实例
							ch.pipeline().addLast(new EchoClientHandler());
						}
					});
			//连接到远程节点，阻塞等待直到连接完成
			ChannelFuture future = bootstrap.connect().sync();
			// 阻塞，直到 Channel 关闭
			future.channel().closeFuture().sync();
		} finally {
			//关闭线程池并且释放所有的资源
			group.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		if (num < 0) {
			log.error("Usage: " + EchoServer.class.getSimpleName() + " <port>");
		} else {
			log.info("Usage: " + num + " <port>");
		}
		new EchoClient("localhost", num).start();
	}
}
